package de.breitbeil.jbooking.task;

import java.io.File;
import java.io.FileInputStream;
import java.util.Calendar;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;

import de.breitbeil.jbooking.ui.form.FtpCalendarFormObject;
import de.breitbeil.jbooking.util.CalendarToImage;

public class FtpCalendarTask extends AbstractTask<Void, Void> {

    private FtpCalendarFormObject formObject;
    
    public FtpCalendarTask(FtpCalendarFormObject formObject) {
        super("ftpCalendarTask");
        
        this.formObject = formObject;
    }
    
    @Override
    protected Void doInBackground() throws Exception {
        
        File imageFile = null;
        FileInputStream inputStream = null;
        try {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(formObject.getFirstDisplayedDay());
            
            imageFile = File.createTempFile("JBooking"+new Object(), "."+formObject.getSuffix());
            CalendarToImage.writeToImage(calendar, imageFile.getAbsolutePath());
            imageFile = new File(imageFile.getAbsolutePath());
            inputStream = new FileInputStream(imageFile);
            
            FTPClient ftp = new FTPClient();
            ftp.setDefaultPort(formObject.getPort());
            ftp.connect(formObject.getHost());
            ftp.login(formObject.getUsername(), formObject.getPassword());

            ftp.enterLocalPassiveMode();
            
            ftp.setFileTransferMode(FTP.BINARY_FILE_TYPE);
            ftp.setFileType(FTP.BINARY_FILE_TYPE);
            
            if(!ftp.storeFile(getFileName(), inputStream)){
                throw new RuntimeException("File transfer failed: " + ftp.getReplyString());
            }
            
            inputStream.close();
            inputStream = null;
            
            ftp.quit();
        }
        finally {
            if(inputStream != null) {
                inputStream.close();
            }
            // Delete temporary file
            if(imageFile != null) {
                //imageFile.delete();
            }
        }
        
        return null;
    }

    private String getFileName() {
        String filename = formObject.getRemoteFile();
        String suffix = formObject.getSuffix();
        
        if(!filename.toLowerCase().endsWith(suffix.toLowerCase())) {
            filename = filename + "." + suffix;
        }
        
        return filename;
    }

}
